<?php

namespace app\api\controller;

use addons\third\model\Third;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Http;
use fast\Random;
use fast\Snowflake;
use think\Config;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Validate;
use wxApp\WxApp;
use function fast\e;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third', 'get_car_shop_info', 'get_home_page','email_register'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account 账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 邮箱注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email 邮箱
     * @param string $mobile 手机号
     * @param string $code 验证码
     */
    public function email_register()
    {


        $password = $this->request->post('password');
        $email = $this->request->post('account');
        if (!$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        $pid = $this->request->post("pid");
        if ($pid != "") {
            $puser = Db::name("user")->field("id,pid,openid")->where("id",$pid)->find();
            if (!$puser) {
                $this->error("推荐人不存在");
            }
            if (!$puser["openid"]){
                $puser2 = Db::name("user")->field("id,openid")->where("id",$puser["pid"])->find();
                if (!$puser2["openid"]) {
                    $this->error("推荐人id无效");

                }
            }
        }




        $ret = $this->auth->email_register($password, $email,["pid"=>$pid]);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }

    }



    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email 邮箱
     * @param string $mobile 手机号
     * @param string $code 验证码
     */
    public function register()
    {


        $user = $this->auth->getUser();
        if ($user["shop_status"] == 1) {
            $this->error("实名信息已审核，无法修改");
        }

        $nickname = $this->request->post('nickname');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');

        $user->name = $this->request->post('name');
        $user->mobile = $this->request->post('mobile');
        $user->shop_name = $this->request->post('shop_name');
        $user->city = $this->request->post('city');
        $user->shop_address = $this->request->post('shop_address');
        $user->id_photo = $this->request->post('id_photo');
        $user->license = $this->request->post('license');
        $user->shop_status = 0;
        $user->vip_createtime_time = time();

        $user->nickname = $nickname;
        $user->avatar = $avatar;
        $user->save();
        $this->success();

    }


    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }


    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar 头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio 个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();

        $nickname = $this->request->post('nickname');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        $user->nickname = $nickname;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email 邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code Code码
     */
    public function third()
    {
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $data = (new WxApp)->GetOpenid($code);
        $data = json_decode($data, true);
        if (!isset($data["openid"])) {
            $this->error("openid 获取失败");
        }

        $user = Db::name("user")->where("openid", $data["openid"])->find();

        if (!empty($user)) {
            $ret = $this->auth->direct($user["id"]);
            if ($ret) {
                $data = ['userinfo' => $this->auth->getUserinfo()];
                $this->success(__('Logged in successful'), $data);
            } else {
                $this->error($this->auth->getError());
            }
        } else {
            $pid = $this->request->post("pid");
//            $this->error($pid);
            $ret = $this->auth->register($data["openid"], ["pid" => $pid]);
            if ($ret) {
                $data = ['userinfo' => $this->auth->getUserinfo()];
                $this->success(__('Sign up successful'), $data);
            } else {
                $this->error($this->auth->getError());
            }
        }


    }

    //获取微信手机号
    public function get_phone()
    {
        $code = $this->request->post("code");
        $data = (new WxApp)->getPhoneNumber($code, $this->auth->openid);
        $data = json_decode($data, true);
        if ($data["errcode"] == 0) {
            $this->success("", $data["phone_info"]);
        } else {
            $this->error($data["errmsg"]);
        }


    }

    //获取小程序带参数二维码
    public function get_qcode()
    {

        $scene = input("scene");
        $scene = "pid={$this->auth->id}&" . $scene;

        $page = input("page");

        $data = (new WxApp)->getWxacodeUnlimit($scene, $page);
        $this->success("", $data);


    }

    //推荐码
    public function referral_code()
    {
        $scene = "pid={$this->auth->id}";

        $page = input("page");
        $data = (new WxApp)->getWxacodeUnlimit($scene, $page);
        $this->success("", $data);


    }


    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $newpassword 新密码
     * @param string $captcha 验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type", "mobile");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 获取用户信息
     */
    public function getUserInfo()
    {
        $user = Db::name("user")
            ->field("id,level,nickname,avatar,margin,money,prevtime,name,mobile,shop_name,city,shop_address,id_photo,license,pid")
            ->field("vip_status,vip_exp_time,shop_audit_time,shop_status,rejection_info,createtime")
            ->where("id", $this->auth->id)->find();

        $user_level = Db::name("user_level")
            ->where("id", $user["level"])
            ->find();
        //关注数
        $user["follow_num"] = Db::name("follow")->where("user_id", $this->auth->id)->count();

        //粉丝数
        $user["fans_num"] = Db::name("follow")->where("follow_user_id", $this->auth->id)->count();

        //收藏车源数量
        $user["collection_num"] = Db::name("car_collection")->where("user_id", $this->auth->id)->count();

        $user["level"] = $user_level;
        $vip = Db::name("user_level")->where("id", 1)->find();
        $user["vip_config"] = $vip;

//        $site = Config::get('site');
//        halt($site);
        $user["version"] = "1.1.0";
        $user["shop_code"] = "TCW".($user["id"]+100000);

        $yanqi = strtotime("2025-08-31 23:59:59");
        if (strtotime(date("Y-m-d H:i:s")) > $yanqi) {
            if ($user["vip_status"] == 1) {
                if (date("Y-m-d H:i:s") > $user["vip_exp_time"]) {
                    $user = Db::name("user")->where("id", $this->auth->id)->update(["vip_status" => 3]);
                }
            }
        } else {
            //会员赠送日期
            if (strtotime($user["vip_exp_time"]) < $yanqi) {
                $user = Db::name("user")->where("id", $this->auth->id)->update([
                    "level" => 1,
                    "vip_status" => 1,
                    "vip_exp_time" => "2025-08-31 23:59:59"]);
            }
        }


        $comment_num = Db::name("circle_comment")
            ->alias("c")
            ->field("c.*")
            ->join('circle_info ci', 'ci.id = c.circle_info_id')
            ->where("ci.user_id", $this->auth->id)
            ->where("c.status", 0)
            ->order("c.id desc")
            ->count();
        $user["comment_num"] = $comment_num;

        //推荐人信息
        $user["p_vip_status"] = 0;
        $user["p_mobile"] = "";
        if ($user["pid"] > 0) {
            $puser = Db::name("user")->field("mobile,vip_status,vip_exp_time")->where("id",$user["pid"])->find();
            if ($puser) {
                if ($puser["vip_exp_time"] > date("Y-m-d H:i:s")) {
                    $user["p_vip_status"] = 1;
                }
                $user["p_mobile"] = $puser["mobile"];
            }


        }


        $this->success("", $user);
    }

    //账单
    public function user_money_log()
    {

        $limit = input("limit");
        if (empty($limit)) {
            $limit = 10;
        }
        $page = input("page");
        if (empty($page)) {
            $page = 1;
        }
        $offset = ($page - 1) * $limit;

        $list = Db::name("user_bill")
            ->where("user_id", $this->auth->id)
            ->order("id desc")
            ->limit("$offset,$limit")
            ->select();
        $this->success('请求成功', $list);
    }

    //发起提现
    public function draw_money()
    {
        $money = input("post.money");
        if (empty($money)) {
            $this->error("参数错误");
        }

        $userInfo = Db::name("user")->where("id", $this->auth->id)->find();

        if ($money > $userInfo["money"]) {
            $this->error("余额不足");
        }
        Db::startTrans();
        try {

            $user = Db::name("user")->where("id", $this->auth->id)->dec("money", $money)->update();
            if (!$user) {
                $this->error("余额不足");
            }

            $snowflake = new Snowflake($this->auth->id, 1577836800000, 10, 12); // 10位节点ID，12位序列号，起始时间为2020-01-01 00:00:00
            $orderNumber = $snowflake->nextId();
            $data["order_no"] = $orderNumber;
            $data["user_id"] = $this->auth->id;
            $data["before"] = $userInfo["money"];
            $userInfo = Db::name("user")->where("id", $this->auth->id)->find();
            $data["after"] = $userInfo["money"];
            $data["money"] = $money * -1;
            $data["source"] = 0;
            $data["audit_status"] = 0; //审核状态 0未审核 1通过 2驳回 提现的时候使用
            $data["createtime"] = time();

            $result = Db::name("user_bill")->insertGetId($data);
            if ($result) {
                Db::commit();
                $this->success("提现已发起，等待后台审核");
            } else {
                $this->error("下单失败，请稍后再试");
                Db::rollback();
            }
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error("服务超时请稍后再试");
        }
    }

    //个人主页
    public function get_home_page()
    {
        $user_id = input("user_id");
        $user = Db::name("user")
            ->field("id,nickname,shop_name,city,mobile,avatar,prevtime")
            ->where("id", $user_id)->find();
        if (empty($user)) {
            $this->error("用户信息不存在");
        }
        $user["shop_code"] = "TCW".($user["id"]+100000);
        $data["user_info"] = $user;



        //发布的车源数
        $data["car_old_num"] = Db::name("car_old")->where("status", 1)->where("user_id", $user_id)->count();

        //关注数
        $data["follow_num"] = Db::name("follow")->where("user_id", $user_id)->count();

        //粉丝数
        $data["fans_num"] = Db::name("follow")->where("follow_user_id", $user_id)->count();

        //圈子数
        $data["circle_num"] = Db::name("circle_info")->where("status", 1)->where("user_id", $user_id)->count();

        //是否关注
        $data["is_follow"] = Db::name("follow")->where("user_id", $this->auth->id)->where("follow_user_id", $user_id)->count();


        $this->success("", $data);
    }

    //关注
    public function follow_post()
    {
        $user_id = input("post.user_id");

        if ($user_id == $this->auth->id) {
            $this->error("自己个儿不能关注自己个儿");
        }


        $user = Db::name("user")
            ->field("nickname,shop_name,city")
            ->where("id", $user_id)->find();
        if (empty($user)) {
            $this->error("用户信息不存在");
        }
        $res = Db::name("follow")
            ->where("user_id", $this->auth->id)
            ->where("follow_user_id", $user_id)
            ->find();
        if (!empty($res)) {
            $this->error("关注失败");
        }

        $data["user_id"] = $this->auth->id;
        $data["follow_user_id"] = $user_id;
        $data["createtime"] = time();
        $res = Db::name("follow")->insert($data);
        if ($res) {
            $this->success("关注成功");
        } else {
            $this->error("关注失败");
        }

    }

    //取消关注
    public function cancel_follow_post()
    {
        $user_id = input("post.user_id");
        $user = Db::name("user")
            ->field("nickname,shop_name,city")
            ->where("id", $user_id)->find();
        if (empty($user)) {
            $this->error("用户信息不存在");
        }

        $res = Db::name("follow")
            ->where("user_id", $this->auth->id)
            ->where("follow_user_id", $user_id)
            ->delete();
        if ($res) {
            $this->success("已取消");
        } else {
            $this->error("取消失败");
        }

    }

    //我的车源 私聊统计
    public function car_chat_add()
    {

        $car_old_id = input("car_old_id");
        $detail = Db::name("car_old")
            ->where("id", $car_old_id)
            ->find();
        if (empty($detail)) {
            $this->error("车源不存在");
        }
        Db::name("car_old")->where("id", $car_old_id)->inc("chat_num")->update();
        $car_chat = Db::name("car_chat")->where([
            "user_id" => $this->auth->id,
            "get_id" => $detail["user_id"],
            "car_old_id" => $car_old_id,
        ])->find();

        if (!empty($car_chat)) {
            Db::name("car_chat")->where("id", $car_chat["id"])->inc("num")->update();
            $this->success("创建成功");
        }


        $car_chat = Db::name("car_chat")->insert([
            "user_id" => $this->auth->id,
            "get_id" => $detail["user_id"],
            "car_old_id" => $car_old_id,
            "num" => 1,
            "createtime" => time(),
        ]);

        if ($car_chat) {
            $this->success("创建成功");
        } else {
            $this->error("创建失败");
        }

    }

    //我的车源 电话拨打统计
    public function car_phone_add()
    {

        $car_old_id = input("car_old_id");
        $detail = Db::name("car_old")
            ->where("id", $car_old_id)
            ->find();
        if (empty($detail)) {
            $this->error("车源不存在");
        }
        Db::name("car_old")->where("id", $car_old_id)->inc("dial_num")->update();
        $car_chat = Db::name("car_phone")->where([
            "user_id" => $this->auth->id,
            "get_id" => $detail["user_id"],
            "car_old_id" => $car_old_id,
        ])->find();

        if (!empty($car_chat)) {
            Db::name("car_phone")->where("id", $car_chat["id"])->inc("num")->update();
            $this->success("创建成功");
        }


        $car_chat = Db::name("car_phone")->insert([
            "user_id" => $this->auth->id,
            "get_id" => $detail["user_id"],
            "car_old_id" => $car_old_id,
            "num" => 1,
            "createtime" => time(),
        ]);

        if ($car_chat) {
            $this->success("创建成功");
        } else {
            $this->error("创建失败");
        }

    }

    //我的车源 浏览统计
    public function car_browse_add()
    {

        $car_old_id = input("car_old_id");
        $detail = Db::name("car_old")
            ->where("id", $car_old_id)
            ->find();
        if (empty($detail)) {
            $this->error("车源不存在");
        }
        Db::name("car_old")->where("id", $car_old_id)->inc("browse_num")->update();
        $car_chat = Db::name("car_browse")->where([
            "user_id" => $this->auth->id,
            "get_id" => $detail["user_id"],
            "car_old_id" => $car_old_id,
        ])->find();

        if (!empty($car_chat)) {
            Db::name("car_browse")->where("id", $car_chat["id"])->inc("num")->update();
            $this->success("创建成功");
        }


        $car_chat = Db::name("car_browse")->insert([
            "user_id" => $this->auth->id,
            "get_id" => $detail["user_id"],
            "car_old_id" => $car_old_id,
            "num" => 1,
            "createtime" => time(),
        ]);

        if ($car_chat) {
            $this->success("创建成功");
        } else {
            $this->error("创建失败");
        }

    }

    //我的车源 私聊记录
    public function car_chat_list()
    {

        //分页
        $limit = input("limit");
        if (empty($limit)) {
            $limit = 10;
        }
        $page = input("page");
        if (empty($page)) {
            $page = 1;
        }
        $offset = ($page - 1) * $limit;

        $car_old_id = input("car_old_id");
        $list = Db::name("car_chat")
            ->field("car_chat.*")
            ->field("u.name,u.nickname,u.shop_name,u.avatar")
            ->join('user u', 'u.id = car_chat.user_id')
            ->where("car_chat.car_old_id", $car_old_id)
            ->limit("$offset,$limit")
            ->select();
        $this->success("ok", $list);
    }

    //我的车源 电话拨打记录
    public function car_phone_list()
    {

        //分页
        $limit = input("limit");
        if (empty($limit)) {
            $limit = 10;
        }
        $page = input("page");
        if (empty($page)) {
            $page = 1;
        }
        $offset = ($page - 1) * $limit;

        $car_old_id = input("car_old_id");
        $list = Db::name("car_phone")
            ->field("car_phone.*")
            ->field("u.name,u.nickname,u.shop_name,u.avatar")
            ->join('user u', 'u.id = car_phone.user_id')
            ->where("car_phone.car_old_id", $car_old_id)
            ->limit("$offset,$limit")
            ->select();
        $this->success("ok", $list);
    }

    //我的车源 浏览记录
    public function car_browse_list()
    {

        //分页
        $limit = input("limit");
        if (empty($limit)) {
            $limit = 10;
        }
        $page = input("page");
        if (empty($page)) {
            $page = 1;
        }
        $offset = ($page - 1) * $limit;

        $car_old_id = input("car_old_id");
        $list = Db::name("car_browse")
            ->field("car_browse.*")
            ->field("u.name,u.nickname,u.shop_name,u.avatar")
            ->join('user u', 'u.id = car_browse.user_id')
            ->where("car_browse.car_old_id", $car_old_id)
            ->limit("$offset,$limit")
            ->select();
        $this->success("ok", $list);
    }

    //我的车源 收藏记录
    public function car_collection_list()
    {

        //分页
        $limit = input("limit");
        if (empty($limit)) {
            $limit = 10;
        }
        $page = input("page");
        if (empty($page)) {
            $page = 1;
        }
        $offset = ($page - 1) * $limit;

        $car_old_id = input("car_old_id");
        $list = Db::name("car_collection")
            ->field("car_collection.*")
            ->field("u.name,u.nickname,u.shop_name,u.avatar")
            ->join('user u', 'u.id = car_collection.user_id')
            ->where("car_collection.car_old_id", $car_old_id)
            ->limit("$offset,$limit")
            ->select();
        $this->success("ok", $list);
    }

    //收藏
    public function collection_post()
    {
        $car_old_id = input("post.car_old_id");

        $res = Db::name("car_collection")
            ->where("user_id", $this->auth->id)
            ->where("car_old_id", $car_old_id)
            ->find();
        if (!empty($res)) {
            $this->error("已收藏");
        }
        $detail = Db::name("car_old")
            ->where("id", $car_old_id)
            ->find();

        $data["user_id"] = $this->auth->id;
        $data["car_old_id"] = $car_old_id;
        $data["get_id"] = $detail["user_id"];
        $data["createtime"] = time();
        $res = Db::name("car_collection")->insert($data);
        Db::name("car_old")->where("id", $car_old_id)->inc("collection_num")->update();
        if ($res) {
            $this->success("已收藏");
        } else {
            $this->error("收藏失败");
        }

    }

    //取消收藏
    public function cancel_collection_post()
    {
        $car_old_id = input("post.car_old_id");

        $res = Db::name("car_collection")
            ->where("user_id", $this->auth->id)
            ->where("car_old_id", $car_old_id)
            ->delete();
        Db::name("car_old")->where("id", $car_old_id)->dec("collection_num")->update();
        if ($res) {
            $this->success("已取消");
        } else {
            $this->error("取消失败");
        }

    }

    //收藏列表
    public function collection_list()
    {
        $limit = input("limit");
        if (empty($limit)) {
            $limit = 10;
        }
        $page = input("page");
        if (empty($page)) {
            $page = 1;
        }
        $offset = ($page - 1) * $limit;
        $list = Db::name("car_collection")
            ->alias("c")
            ->field("c.createtime,u.id,u.car_brand_name,u.car_series_name,u.car_models_name,u.car_image,u.registration_time,u.city")
            ->field("u.price,u.cut_price,u.is_price,u.test_report_file,u.odometer_km,u.factory_date,u.old_type,u.type")
            ->join('car_old u', 'u.id = c.car_old_id')
            ->where("c.user_id", $this->auth->id)
            ->order("id desc")
            ->limit("$offset,$limit")
            ->select();
        $this->success('请求成功', $list);
    }

    //关注用户 列表
    public function my_follow_list()
    {
        $limit = input("limit");
        if (empty($limit)) {
            $limit = 10;
        }
        $page = input("page");
        if (empty($page)) {
            $page = 1;
        }
        $offset = ($page - 1) * $limit;
        $list = Db::name("follow")
            ->alias("f")
            ->field("f.*,u.nickname,u.avatar,u.shop_name,u.city")
            ->join('user u', 'u.id = f.follow_user_id')
            ->where("user_id", $this->auth->id)
            ->order("id desc")
            ->limit("$offset,$limit")
            ->select();
        $this->success('请求成功', $list);
    }

    //我的粉丝
    public function follow_my_list()
    {
        $limit = input("limit");
        if (empty($limit)) {
            $limit = 10;
        }
        $page = input("page");
        if (empty($page)) {
            $page = 1;
        }
        $offset = ($page - 1) * $limit;
        $list = Db::name("follow")
            ->alias("f")
            ->field("f.*,u.nickname,u.avatar,u.shop_name,u.city")
            ->field("(select count(*) from follow where follow_user_id=f.user_id and user_id=f.follow_user_id) as is_follow")
            ->join('user u', 'u.id = f.user_id')
            ->where("follow_user_id", $this->auth->id)
            ->order("id desc")
            ->limit("$offset,$limit")
            ->select();
        $this->success('请求成功', $list);
    }

    //我的服务
    public function my_service()
    {
        $type = input("type");
        $list = Db::name("service");
        $list = $list->where("type", $type)->order("id desc");

        //1定金保障 2会员权益 3入会须知 4视频教程 5功能介绍 6隐私协议 7用户协议
        if ($type == 1 || $type == 2) {
            $list = $list->field("id,file")->find();
            $this->success('请求成功', $list);
        }
        if ($type == 3 || $type == 6 || $type == 7 || $type == 8) {
            $list = $list->field("id,info")->find();
            $this->success('请求成功', $list);
        }

        $list = $list->select();
        $this->success('请求成功', $list);
    }

    //建议反馈
    public function proposal_post()
    {
        $data = input("post.");
        $data["user_id"] = $this->auth->id;
        $data["createtime"] = time();
        $res = Db::name("proposal")->insert($data);
        if ($res) {
            $this->success("提交成功");
        } else {
            $this->error("提交失败");
        }

    }

    //根据ids 数组返回用户信息列表
    public function get_user_infos()
    {
        $ids = input("ids/a");
        if (empty($ids)) {
            $this->success('请求成功', []);
        }
        $list = Db::name("user")
            ->where("id", "in", $ids)
            ->field("id,nickname,name,mobile,shop_name,city,avatar")
            ->select();
        $this->success('请求成功', $list);
    }


    /**
     * 返回车商信息 车源统计
     */
    public function get_car_shop_info()
    {
        $user_id = input("user_id");
        $user = Db::name("user")
            ->field("id,nickname,avatar,name,mobile,shop_name,city,shop_address,id_photo,license")
            ->where("id", $user_id)->find();

        //车源数
        $user["car_old_num"] = Db::name("car_old")->where("user_id", $user_id)->count();
//        if ($this->auth->id == $user_id) {
//            //车源数
//            $user["car_old_num"] = Db::name("car_old")->where("user_id", $user_id)->count();
//        } else {
//            //车源数
//            $user["car_old_num"] = Db::name("car_old")->where("status", 1)->where("user_id", $user_id)->count();
//        }


        //成交数
        $user["order_deal_num"] = Db::name("car_old")->where("user_id", $user_id)->where("status", 0)->count();
        $user["shop_code"] = "TCW".($user["id"]+100000);
        $this->success("", $user);
    }

    //平台通知
    public function notice_list()
    {
        $limit = input("limit");
        if (empty($limit)) {
            $limit = 10;
        }
        $page = input("page");
        if (empty($page)) {
            $page = 1;
        }
        $offset = ($page - 1) * $limit;
        $list = Db::name("notice")
            ->where("user_id",$this->auth->id)
            ->whereOr('user_id', null)
            ->order("id desc")
            ->limit("$offset,$limit")
            ->select();
        $this->success('请求成功', $list);
    }

    //平台通知详情
    public function notice_detail()
    {
        $id = input("id");

        $list = Db::name("notice")
            ->where("id", $id)
            ->find();
        $this->success('请求成功', $list);
    }

    //互动消息 （评论消息）
    public function interact_list()
    {
        $limit = input("limit");
        if (empty($limit)) {
            $limit = 10;
        }
        $page = input("page");
        if (empty($page)) {
            $page = 1;
        }
        $offset = ($page - 1) * $limit;
        $list = Db::name("circle_comment")
            ->alias("c")
            ->field("c.*")
            ->field("u.nickname,u.avatar,u.mobile")
            ->join('user u', 'u.id = c.user_id')
            ->join('circle_info ci', 'ci.id = c.circle_info_id')
            ->where("ci.user_id", $this->auth->id)
            ->order("c.id desc")
            ->limit("$offset,$limit")
            ->select();
        $this->success('请求成功', $list);
    }


    //消息通知
    public function unread_msg_notice()
    {

        $user = input("user_id");
        $user = Db::name("user")->where("id", $user)->find();
        if (empty($user)) {
            $this->error("用户信息信息不存在");
        }
        $data_template = [
            "thing4" => ["value" => $user["nickname"]],
            "time5" => ["value" => date("Y-m-d H:i:s")]
        ];
        (new WxApp)->sendMessage("D5ZU2buCxG4IQg1je_2dvEoPhYEM6I4TnFMJ1x1XSfg", $user["openid"], $data_template);
        $this->success("消息发送成功");
    }


    //出口服务商列表
    public function shop_list() {


        //分页
        $limit = input("limit");
        if (empty($limit)) {
            $limit = 10;
        }
        $page = input("page");
        if (empty($page)) {
            $page = 1;
        }
        $offset = ($page-1)*$limit;
        $list = Db::name("user")
            ->field("shop_logo,shop_name,city,shop_address,shop_intro,mobile,is_export_shop")
            ->where("is_export_shop",1);
        $list =  $list->limit("$offset,$limit")
            ->select();
//        echo Db::getLastSql();
        $this->success('请求成功',$list);
    }


    //下级用户列表
    public function subordinate_user_list()
    {
        $limit = input("limit");
        if (empty($limit)) {
            $limit = 10;
        }
        $page = input("page");
        if (empty($page)) {
            $page = 1;
        }
        $offset = ($page - 1) * $limit;
        $user_id = input("user_id");
        $list = Db::name("user")
            ->field("id,nickname,name,mobile,avatar,pid")
            ->where("pid", $user_id)
            ->order("id desc")
            ->limit("$offset,$limit")
            ->select();
        $this->success('请求成功', $list);
    }


}


